package com.lagou.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.lagou.handler.CodeBlockHandler;
import com.lagou.pojo.AuthCode;
import com.lagou.service.CodeService;
import com.lagou.util.DateFormatUtil;
import com.lagou.util.ResponseData;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;

@RestController
@RequestMapping("/code")
public class CodeController {

    @Autowired
    private CodeService codeService;

    /**
     * 获取验证码
     */

    @GetMapping("/create/{email}")
    @SentinelResource(value = "create",blockHandlerClass = CodeBlockHandler.class,blockHandler = "handleException",
            fallback = "handleError",fallbackClass = CodeBlockHandler.class)
    public ResponseData create(@PathVariable String email){
        //int i = 1/0;
        codeService.sendCode(email);
        return ResponseData.success("发送验证码成功");
    }


    /**
     * 判断验证码是否有效
     */
    @GetMapping("/check")
    public ResponseData checkCode(String email, String code, String submitTime){
        AuthCode authCode = codeService.getAuthCodeByEmailAndCode(email, code);
        if (authCode == null){
            return ResponseData.fail("验证码错误");
        }

        Date date = DateFormatUtil.string2Date("yyyy-MM-dd HH:mm:ss", submitTime);
        Date expiretime = authCode.getExpiretime();
        if (expiretime.compareTo(date)<0){
            ResponseData responseData = ResponseData.fail("验证码已过期");
            return responseData;
        }

        return ResponseData.success("验证成功");
    }
}
